// Package sms
// Created by GoLand
// @User: lenora
// @Date: 2023/12/11
// @Time: 16:10

package sms

import (
	"context"
)

type BaseService interface {
	Send(ctx context.Context, tplId string, args []string, phone ...string) error
}

type Service interface {
	Send(ctx context.Context, tplId string, args []string, phone ...string) error
}

type TopService struct {
	limiter  RateLimiter
	auth     AuthService
	svcs     []BaseService
	idx      uint64 //当前使用节点下标
	failover TimeoutFailover
}

func NewTopService(l RateLimiter /* auth AuthService, svc []BaseService, f TimeoutFailover*/) Service {
	return &TopService{
		limiter: l,
		//auth:     auth,
		//svcs:     svc,
		//failover: f,
	}
}

// 轮询服务商发送
func (t *TopService) Send(ctx context.Context, tplId string, args []string, phone ...string) error {
	//限流器
	if t.limiter != nil {
		if err := t.limiter.Limit(ctx); err != nil {
			return err

		}
	}

	//短信tpl鉴权
	if t.auth != nil {
		tpl, err := t.auth.Decode(tplId)
		if err != nil {
			return err
		}
		tplId = tpl
	}

	return t.failoverSend(ctx, tplId, args, phone...)
}

// 验证服务商是否存在异常后发送

func (t *TopService) SendV1(ctx context.Context, tplId string, args []string, phone ...string) error {
	//限流器
	if t.limiter != nil {
		if err := t.limiter.Limit(ctx); err != nil {
			return err

		}
	}

	//短信tpl鉴权
	if t.auth != nil {
		tpl, err := t.auth.Decode(tplId)
		if err != nil {
			return err
		}
		tplId = tpl
	}

	svc := t.failover.Check(t.svcs)
	err := svc.Send(ctx, tplId, args, phone...)
	switch err {
	case nil:
		t.failover.ResetCount()
		return nil
	case context.DeadlineExceeded:
		//超时  是否自动切换?
		t.failover.CountAdd()
	default:
		//其余错误  考虑处理方式

	}
	return nil
}
